import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
    state: () => ({
        // 应用配置
        title: 'PMall积分商城',
        version: '1.0.0',

        // 界面状态
        sidebarCollapsed: false,
        theme: 'light' as 'light' | 'dark',
        loading: false,

        // 系统信息
        systemInfo: {
            os: '',
            browser: '',
            version: '',
        },
    }),

    getters: {
        // 应用标题
        appTitle: (state) => state.title,

        // 是否暗色主题
        isDarkTheme: (state) => state.theme === 'dark',

        // 是否加载中
        isLoading: (state) => state.loading,
    },

    actions: {
        // 设置加载状态
        setLoading(loading: boolean) {
            this.loading = loading
        },

        // 切换侧边栏
        toggleSidebar() {
            this.sidebarCollapsed = !this.sidebarCollapsed
        },

        // 设置侧边栏状态
        setSidebarCollapsed(collapsed: boolean) {
            this.sidebarCollapsed = collapsed
        },

        // 切换主题
        toggleTheme() {
            this.theme = this.theme === 'light' ? 'dark' : 'light'
            // 保存到localStorage
            localStorage.setItem('theme', this.theme)
        },

        // 设置主题
        setTheme(theme: 'light' | 'dark') {
            this.theme = theme
            localStorage.setItem('theme', theme)
        },

        // 初始化应用
        initApp() {
            // 从localStorage恢复主题
            const savedTheme = localStorage.getItem('theme') as 'light' | 'dark'
            if (savedTheme) {
                this.theme = savedTheme
            }

            // 获取系统信息
            this.getSystemInfo()
        },

        // 获取系统信息
        getSystemInfo() {
            const userAgent = navigator.userAgent

            // 检测操作系统
            if (userAgent.includes('Windows')) {
                this.systemInfo.os = 'Windows'
            } else if (userAgent.includes('Mac')) {
                this.systemInfo.os = 'macOS'
            } else if (userAgent.includes('Linux')) {
                this.systemInfo.os = 'Linux'
            } else {
                this.systemInfo.os = 'Unknown'
            }

            // 检测浏览器
            if (userAgent.includes('Chrome')) {
                this.systemInfo.browser = 'Chrome'
            } else if (userAgent.includes('Firefox')) {
                this.systemInfo.browser = 'Firefox'
            } else if (userAgent.includes('Safari')) {
                this.systemInfo.browser = 'Safari'
            } else {
                this.systemInfo.browser = 'Unknown'
            }

            this.systemInfo.version = navigator.appVersion
        },
    },
})
